//
//  chongzhiVC.m
//  YaoHeAPP
//
//  Created by xyh on 16/4/26.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "chongzhiVC.h"
#import "Masonry.h"

#import "Controller.h"

#import "TongYong.h"

#import "bankcardCell.h"


#import "UIImageView+WebCache.h"

#define screenWidth self.view.frame.size.width
#define screenHeight self.view.frame.size.height
#define bgVCcolor [UIColor colorWithRed:235.f/255.f green:235.f/255.f blue:244.f/255.f alpha:1]


@interface chongzhiVC ()<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>
{
    UIView *topsmallview;
    NSMutableArray *arrayList;
    
    UIView *bigView;
    
    UILabel *daijishi;
    
    //倒计时
    NSMutableArray *totalLastTime;
    
    NSTimer *timer;
    
    UIView *top;
}
@property(nonatomic,strong) UITableView *tableview;  //定义大表格
@end

@implementation chongzhiVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"chongzhiVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"chongzhiVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
    
}


//视图将要消失的时候将定时器关闭
-(void)viewDidDisappear:(BOOL)animated
{
    if (timer.isValid) {
        [timer invalidate];
    }
    timer=nil;
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(kNavigationBarHeight);  make.right.offset(0);
    }];
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"账户充值";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(self.view.frame.size.width/2-70);
        make.width.offset(140);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backLogin) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.top.offset(31);
    }];
    
//    
//    topsmallview=[[UIView alloc]initWithFrame:CGRectMake(0, 60, screenWidth, 36)];
//    topsmallview.backgroundColor=[UIColor colorWithRed:174/255.0 green:179/255.0 blue:180/255.0  alpha:1];
//    [self.view addSubview:topsmallview];
//    [self.view bringSubviewToFront:topsmallview];
//    
//    UILabel *TIT=[[UILabel alloc]init];
//    TIT.frame=CGRectMake(5, 3, self.view.frame.size.width-30, 30);
//    TIT.font=[UIFont systemFontOfSize:12];
//    TIT.textAlignment=NSTextAlignmentCenter;
//    TIT.textColor=[UIColor colorWithRed:103/255.0 green:107/255.0 blue:108/255.0  alpha:1];
//    TIT.text=@"APP不支持在线网银充值，请使用线下汇款充值";
//    TIT.backgroundColor=[UIColor clearColor];
//    [topsmallview addSubview:TIT];
//    
//    
//    UIButton *bt=[[UIButton alloc]init];
//    bt.frame=CGRectMake(self.view.frame.size.width-30, 8, 20, 20);
//    bt.backgroundColor=[UIColor clearColor];
//    [bt setBackgroundImage:[UIImage imageNamed:@"ic_close_imageviewer"] forState:UIControlStateNormal];
//    [bt addTarget:self action:@selector(remTit) forControlEvents:UIControlEventTouchUpInside];
//    [topsmallview addSubview:bt];

    
    
    bigView=[[UIView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, screenWidth, screenHeight-kNavigationBarHeight-40)];
    bigView.backgroundColor=[UIColor clearColor];
    [self.view addSubview:bigView];
    

    
    UIView *redview=[[UIView alloc]initWithFrame:CGRectMake(0, 17, 5, 20)];
    redview.backgroundColor=[UIColor redColor];
    [bigView addSubview:redview];
    UILabel *tittop=[[UILabel alloc]initWithFrame:CGRectMake(15, 10, screenWidth-10, 30)];
    tittop.textAlignment=NSTextAlignmentLeft;
    tittop.text=@"请汇款至以下账户:";
    tittop.font=[UIFont systemFontOfSize:15];
    [bigView addSubview:tittop];
    
    
    arrayList=[[NSMutableArray alloc]init];
    
    totalLastTime=[[NSMutableArray alloc]init];
    
    [self banklist];
    
    //创建表格
    _tableview=[[UITableView alloc]initWithFrame:CGRectMake(0,50, self.view.frame.size.width, screenHeight-kNavigationBarHeight-40-50) style:UITableViewStylePlain];
    _tableview.backgroundColor= [UIColor colorWithRed:230/255.0 green:232/255.0 blue:241/255.0  alpha:1];
    _tableview.delegate=self;
    _tableview.dataSource=self;
    _tableview.separatorStyle=NO;
    [bigView addSubview:_tableview];

    
    
    
    //是从明细过来的  就没有顶部的余额
    if ([self.ismingxi isEqualToString:@"账户明细"]) {
        
        
    }else{
    
        //证明是从余额不足时传过来的  需要修改相关view的坐标 有充值和倒计时显示
        
        top=[[UIView alloc]initWithFrame:CGRectMake(0, 60, screenWidth, 50)];
        top.backgroundColor=[UIColor whiteColor];
        [self.view addSubview:top];
        
        
        //倒计时时间
        UILabel *chongzhijine=[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 30)];
        chongzhijine.font=[UIFont systemFontOfSize:14];
        chongzhijine.textAlignment=NSTextAlignmentLeft;
        chongzhijine.text=@"充值金额";
        chongzhijine.textColor=[UIColor blackColor];
        [top addSubview:chongzhijine];
        
        
        NSString *st=[self.moneyout stringByReplacingOccurrencesOfString:@"元" withString:@""];

        UILabel *chongzhijinetext=[[UILabel alloc]initWithFrame:CGRectMake(screenWidth-200, 10, 170, 20)];
        chongzhijinetext.font=[UIFont systemFontOfSize:12];
        chongzhijinetext.textAlignment=NSTextAlignmentRight;
        chongzhijinetext.text=[NSString stringWithFormat:@"￥%@",st];
        chongzhijinetext.textColor=[UIColor colorWithRed:251/255.0 green:87/255.0 blue:60/255.0  alpha:1];
        [top addSubview:chongzhijinetext];

        
        
        //倒计时时间
        daijishi=[[UILabel alloc]initWithFrame:CGRectMake(screenWidth-100, 30, 90, 20)];
        daijishi.font=[UIFont systemFontOfSize:12];
        daijishi.textAlignment=NSTextAlignmentLeft;
        daijishi.textColor=[UIColor colorWithRed:251/255.0 green:87/255.0 blue:60/255.0  alpha:1];
        [top addSubview:daijishi];

    
        UIImageView *timeimg=[[UIImageView alloc]initWithFrame:CGRectMake(screenWidth-120, 30, 15, 15)];
        timeimg.image=[UIImage imageNamed:@"daojishi"];
        [top addSubview:timeimg];
        
        if (self.timest==nil||self.timest.integerValue==0) {
            
            timeimg.hidden=YES;
            
        } else {
            
            timeimg.hidden=NO;
            
            NSTimeInterval timestyy = [[NSDate date] timeIntervalSince1970];
            
            NSInteger timeintage=timestyy;
            
            NSInteger timest=self.timest.integerValue;
            
            NSInteger shengyutime=timest-timeintage;
            
            NSInteger miao=shengyutime;
            NSString *stm=[NSString stringWithFormat:@"%ld",(long)miao];
            NSDictionary *dic = @{@"indexPath":[NSString stringWithFormat:@"%i",0],@"lastTime":stm};
            [totalLastTime addObject:dic];
            [self startTimer];
        }
        [UIView animateWithDuration:0.5 animations:^{
            
            bigView.frame = CGRectMake(0, 146-36, screenWidth, screenHeight-146-40+36);
            _tableview.frame=CGRectMake(0, 50, screenWidth,screenHeight-146-40-50+36);
        }];


    }
    
    //下部按钮
    UIView *bootmView=[[UIView alloc]init];
    bootmView.backgroundColor=[UIColor clearColor];
    bootmView.frame=CGRectMake(0,screenHeight-40, screenWidth, 40);
    [self.view addSubview:bootmView];
    
    
    
    UILabel *leftlabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, screenWidth-20, 30)];
    leftlabel.font=[UIFont systemFontOfSize:14];
    leftlabel.textAlignment=NSTextAlignmentCenter;
    leftlabel.textColor=[UIColor colorWithRed:102/255.0 green:102/255.0 blue:102/255.0  alpha:1];
    [bootmView addSubview:leftlabel];
    NSString *ss=[NSString stringWithFormat:@"如有问题请拨打客服热线:  400-885-0054"];
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc] initWithString:ss];
    NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:@":"].location+1,noteStr.length-12);
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1] range:redRange];
    [leftlabel setAttributedText:noteStr];
    
    UIButton *iphonebut=[[UIButton alloc]initWithFrame:CGRectMake(screenWidth/2, 0, screenWidth/2, 30)];
    iphonebut.backgroundColor=[UIColor clearColor];
    [iphonebut addTarget:self action:@selector(iphoneButAction) forControlEvents:UIControlEventTouchUpInside];
    [bootmView addSubview:iphonebut];
}



//拨打电话
- (void)iphoneButAction {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"友情提醒" message:@"客服工作时间:周一到周五\n(8:30~17:30)" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"呼叫客服", nil];
    [alertView show];
}

#pragma mark ------------开启定时器方法--------
//开启定时器方法：
- (void)startTimer
{
    if (timer.isValid) {
        [timer invalidate];
    }
    timer=nil;
    
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(refreshLessTime) userInfo:@"" repeats:YES];
    
    //    如果不添加下面这条语句，在UITableView拖动的时候，会阻塞定时器的调用
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
    
}

//主要的定时器中的方法，在该方法中，遍历totalLastTime，取出其中保存的lasttime和indexpath，time用来显示，在显示完后自减，indexpath代表对应显示的位置，在一次循环后，将新的time和没有改变的indexpath从新替换totalLastTime 中对应位置的元素，以此保证每一秒执行时，显示time都是最新的。
- (void)refreshLessTime
{
    NSInteger time;
    for (int i = 0; i < totalLastTime.count; i++) {
        
        time = [[[totalLastTime objectAtIndex:i] objectForKey:@"lastTime"] integerValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:[[[totalLastTime objectAtIndex:i] objectForKey:@"indexPath"] integerValue]];
        
        if (time<=0) {
            //提示过期
            NSString *me=[NSString stringWithFormat:@"您的订单已过期"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:me
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:nil];
            alert.tag = 0;
            [alert show];
            //移除该条倒计时
            [totalLastTime removeObjectAtIndex:i];
            
        }else{
            
            
            NSString *ss=[NSString stringWithFormat:@"%@",[self lessSecondToDay:--time]];
            daijishi.text=ss;
            NSDictionary *dic = @{@"indexPath": [NSString stringWithFormat:@"%li",(long)indexPath.section],@"lastTime": [NSString stringWithFormat:@"%lu",(unsigned long)time]};
            [totalLastTime replaceObjectAtIndex:i withObject:dic];
            
        }
        
        
    }
}

- (NSString *)lessSecondToDay:(NSInteger)seconds
{
    //    NSUInteger day  = (NSUInteger)seconds/(24*3600);
    NSInteger hour = (NSInteger)(seconds%(24*3600))/3600;
    NSInteger min  = (NSInteger)(seconds%(3600))/60;
    NSInteger second = (NSInteger)(seconds%60);
    
    NSString *time = [NSString stringWithFormat:@"%ld时%ld分%ld秒",(long)hour,(long)min,(long)second];
    return time;
    
}


////清除提示框
//-(void)remTit
//{
//    
//    [topsmallview   removeFromSuperview];
//    
//    //是从明细过来的  就没有顶部的余额
//    if ([self.ismingxi isEqualToString:@"账户明细"]) {
//        
//        
//        [UIView animateWithDuration:0.5 animations:^{
//            
//            bigView.frame = CGRectMake(0, 60, screenWidth, screenHeight-60-40);
//            _tableview.frame=CGRectMake(0, 50, screenWidth,screenHeight-60-40-50);
//        }];
//        
//        
//    }else{
//    
//    
//        [UIView animateWithDuration:0.5 animations:^{
//            
//            top.frame=CGRectMake(0, 60, screenWidth, 50);
//            bigView.frame = CGRectMake(0, 146-36, screenWidth, screenHeight-146-40+36);
//            _tableview.frame=CGRectMake(0, 50, screenWidth,screenHeight-146-40-50+36);
//        }];
//        
//        
//        
//    }
//    
//    
//    
//}

//获取银行卡信息
-(void)banklist{

    NSMutableDictionary *di=[[NSMutableDictionary alloc]init];
    
    [Controller requestWithURL:BankAccountInfo jsondic:di finishBlock:^(ClassData* data) {
        if ([data.number isEqualToNumber:[NSNumber numberWithInteger:0]])
        {
            [arrayList addObjectsFromArray:data.data];
            
            [self.tableview reloadData];
            
        }
        else
        {
            
        }
    }];

}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return arrayList.count;
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 175;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    //指定cellIdentifier为自定义的cell
    static NSString *CellIdentifier = @"bankcardCell";
    
    //自定义cell类
    bankcardCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //无色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType=UITableViewCellAccessoryNone;
    if (cell == nil) {
        //通过xib的名称加载自定义的cell
        cell = [[[NSBundle mainBundle] loadNibNamed:@"bankcardCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType=UITableViewCellAccessoryNone;
    }
    
    [cell.bankimage sd_setImageWithURL:[NSURL URLWithString:arrayList[indexPath.row][@"bank_icon"]] placeholderImage:[UIImage imageNamed:@""]];
    
    cell.bankName.text=arrayList[indexPath.row][@"bank_type"];
    cell.bankcardid.text=arrayList[indexPath.row][@"bank_account"];
    cell.kaihubank.text=arrayList[indexPath.row][@"bank_name"];
    cell.kaihuname.text=arrayList[indexPath.row][@"account_name"];
    
    
    return cell;
    
}

- (void)backLogin {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (0 == buttonIndex) {
        // do nothing
    } else {
        [self callCustomerService];
    }
}

#pragma mark 呼叫客服
- (void)callCustomerService {
    UIWebView *webview = [[UIWebView alloc] init];
    [webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"tel:4008850054"]]];
    [self.view addSubview:webview];
}

@end
